package com.manage.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.manage.platform.context.UserContext;
import com.manage.platform.dto.*;
import com.manage.platform.dto.query.OrganizeMemberQuery;
import com.manage.platform.dto.query.OrganizeMemberTwoQuery;
import com.manage.platform.entity.*;
import com.manage.platform.exception.CommonException;
import com.manage.platform.mapper.OrganizeMapper;
import com.manage.platform.utils.TreeListOrganizeUtil;
import com.manage.platform.utils.RPage;
import com.manage.platform.vo.*;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * YWD
 * 2025/9/25
 */
@AllArgsConstructor
@Service
public class OrganizeServiceImpl extends ServiceImpl<OrganizeMapper, OrganizeEntity> {

    private final OrganizeMemberServiceImpl organizeMemberServiceImpl;
    private final OrganizeHeadServiceImpl organizeHeadServiceImpl;
    private final OrganizeHeadNextServiceImpl organizeHeadNextServiceImpl;


    public List<OrganizeTreeVo> getOrganizeTree(OrganizeTreeDto dto) {
        List<OrganizeTreeVo> organizeTreeVoList = this.baseMapper.getOrganizeTree(dto);
        if (CollectionUtils.isEmpty(organizeTreeVoList)) return null;
        return TreeListOrganizeUtil.buildMenuTreeList(organizeTreeVoList);
    }


    public RPage<List<OrganizeMemberVo>> getOrganizeMemberPage(OrganizeMemberQuery query) {
        Page<Object> page = PageHelper.startPage(query.getPage(), query.getLimit());
        List<OrganizeMemberVo> list = this.baseMapper.getOrganizeMemberPage(query);
        return RPage.ok(list, query.getPage(), query.getLimit(), page.getTotal());
    }


    @Transactional(rollbackFor = Exception.class)
    public Boolean updateOrganizeMember(List<OrganizeMemberVo> dto) {
        try {
            List<Long> idList = dto.stream().map(OrganizeMemberVo::getId).toList();
            Long orgId = dto.getFirst().getOrgId();
            //删除再新增
            organizeMemberServiceImpl.removeByOrgId(orgId);
            if (!CollectionUtils.isEmpty(idList)) {
                List<OrganizeMemberEntity> list = idList.stream().map(memberId -> {
                    OrganizeMemberEntity organizeMemberEntity = new OrganizeMemberEntity();
                    organizeMemberEntity.setOrgId(orgId)
                            .setMemberId(memberId);
                    return organizeMemberEntity;
                }).toList();
                //批量新增
                return organizeMemberServiceImpl.saveBatch(list);
            }
            return true;
        } catch (Exception e) {
            throw new CommonException("修改失败成员列表失败");
        }
    }


    public Boolean saveOrganizeMember(OrganizeMemberDto dto) {
        return organizeMemberServiceImpl.saveByOrgIdAndMemberId(dto);
    }

    public Boolean deleteOrganizeMember(OrganizeMemberDto dto) {
        return organizeMemberServiceImpl.removeByOrgIdAndMemberId(dto);
    }


    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrganize(OrganizeDto dto) {
        //组织是否重复
        Boolean b = existsSameNameOrganize(dto.getId(), dto.getParentId(), dto.getName());
        if (b) {
            throw new CommonException("该组织名称已存在");
        }
        UserVo userVo = UserContext.getUser();
        dto.setUserId(userVo.getId());
        //1.组织基本信息
        this.baseMapper.saveOrganize(dto);
        //2.组织负责人
        OrganizeHeadDto organizeHeadDto = dto.getOrganizeHeadDto();
        if (ObjectUtil.isNotEmpty(organizeHeadDto)) {
            organizeHeadDto.setOrgId(dto.getId());
            if (StringUtils.isNotEmpty(dto.getPower())) {
                organizeHeadDto.setPower(dto.getPower());
            }
            organizeHeadServiceImpl.save(BeanUtil.copyProperties(dto.getOrganizeHeadDto(), OrganizeHeadEntity.class));
        }
        //3.组织分管负责人
        List<OrganizeHeadNextDto> organizeHeadNextDtoList = dto.getOrganizeHeadNextDtoList();
        if (CollectionUtil.isNotEmpty(organizeHeadNextDtoList)) {
            organizeHeadNextDtoList.forEach(item -> {
                item.setOrgId(dto.getId());
                if (StringUtils.isNotEmpty(dto.getNextPower())) {
                    item.setPower(dto.getNextPower());
                }
            });
            organizeHeadNextServiceImpl.saveBatch(BeanUtil.copyToList(organizeHeadNextDtoList, OrganizeHeadNextEntity.class));
        }
        //4.组织成员
        List<Long> organizeMemberIdList = dto.getOrganizeMemberIdList();
        if (CollectionUtil.isNotEmpty(organizeMemberIdList)) {
            List<OrganizeMemberEntity> list = organizeMemberIdList.stream().map(id -> {
                //构建成员
                OrganizeMemberEntity organizeMemberEntity = new OrganizeMemberEntity();
                organizeMemberEntity.setOrgId(dto.getId());
                organizeMemberEntity.setMemberId(id);
                return organizeMemberEntity;
            }).toList();
            return organizeMemberServiceImpl.saveBatch(list);
        }
        return true;
    }

    public List<CommonVo> getOrganizePartList(String name, String type) {
        return this.baseMapper.getOrganizePartList(name, type);
    }

    public RPage<List<OrganizeMemberVo>> getOrganizeMemberTwoPage(OrganizeMemberTwoQuery query) {
        Page<Object> page = PageHelper.startPage(query.getPage(), query.getLimit());
        List<OrganizeMemberVo> list = this.baseMapper.getOrganizeMemberTwoPage(query);
        return RPage.ok(list, query.getPage(), query.getLimit(), page.getTotal());
    }

    public OrganizeHeadUserVo getOrganizeHeadUser(Long headId) {
        return this.baseMapper.getOrganizeHeadUser(headId);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateOrganize(OrganizeDto dto) {
        //组织是否重复
        Boolean b = existsSameNameOrganize(dto.getId(), dto.getParentId(), dto.getName());
        if (b) {
            throw new CommonException("该组织名称已存在");
        }
        //1.组织基本信息
        this.updateById(BeanUtil.copyProperties(dto, OrganizeEntity.class));
        //2.组织负责人
        OrganizeHeadDto organizeHeadDto = dto.getOrganizeHeadDto();
        //删除再新增
        organizeHeadServiceImpl.removeByOrgId(dto.getId());
        if (ObjectUtil.isNotEmpty(organizeHeadDto)) {
            organizeHeadDto.setOrgId(dto.getId());
            if (StringUtils.isNotEmpty(dto.getPower())) {
                organizeHeadDto.setPower(dto.getPower());
            }
            organizeHeadServiceImpl.save(BeanUtil.copyProperties(dto.getOrganizeHeadDto(), OrganizeHeadEntity.class));
        }
        //3.组织分管负责人
        List<OrganizeHeadNextDto> organizeHeadNextDtoList = dto.getOrganizeHeadNextDtoList();
        //删除再新增
        organizeHeadNextServiceImpl.removeByOrgId(dto.getId());
        if (CollectionUtil.isNotEmpty(organizeHeadNextDtoList)) {
            organizeHeadNextDtoList.forEach(item -> {
                //构建分管负责人
                item.setOrgId(dto.getId());
                if (StringUtils.isNotEmpty(dto.getNextPower())) {
                    item.setPower(dto.getNextPower());
                }
            });
            organizeHeadNextServiceImpl.saveBatch(BeanUtil.copyToList(organizeHeadNextDtoList, OrganizeHeadNextEntity.class));
        }
//        //4.组织成员
//        List<OrganizeMemberVo> organizeMemberIdList = dto.getOrganizeMemberIdList();
//        //删除再新增
//        organizeMemberServiceImpl.removeByOrgId(dto.getId());
//        if (CollectionUtil.isNotEmpty(organizeMemberIdList)) {
//            List<OrganizeMemberEntity> list = organizeMemberIdList.stream().map(memberId -> {
//                //构建成员
//                OrganizeMemberEntity organizeMemberEntity = new OrganizeMemberEntity();
//                organizeMemberEntity.setOrgId(dto.getId());
//                organizeMemberEntity.setMemberId(memberId.getId());
//                return organizeMemberEntity;
//            }).toList();
//            return organizeMemberServiceImpl.saveBatch(list);
//        }
        return true;
    }

    public Boolean deleteOrganize(Long id) {
//        organizeHeadServiceImpl.removeByOrgId(id);
//        organizeHeadNextServiceImpl.removeByOrgId(id);
//        organizeMemberServiceImpl.removeByOrgId(id);
        return removeById(id);
    }

    public Boolean existsSameNameOrganize(Long id, Long parentId, String name) {
        LambdaQueryWrapper<OrganizeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(OrganizeEntity::getIsDeleted, 0)
                .eq(OrganizeEntity::getName, name)
                .eq(OrganizeEntity::getParentId, parentId);
        // 修改操作需要排除自身
        queryWrapper.ne(ObjectUtil.isNotEmpty(id), OrganizeEntity::getId, id);

        List<OrganizeEntity> list = list(queryWrapper);
        System.out.println(list);

        return baseMapper.exists(queryWrapper);
    }

    public OrganizeDetailsVo getOrganizeDetails(Long id) {
        OrganizeDetailsVo organizeDetails = this.baseMapper.getOrganizeDetails(id);
        OrganizeHeadVo organizeHeadDto = organizeDetails.getOrganizeHeadDto();
        //主要负责人权限
        if (ObjectUtil.isNotEmpty(organizeHeadDto)) {
            String power = organizeHeadDto.getPower();
            if (StringUtils.isNotEmpty(power)) {
                organizeDetails.setPower(power);
            }
        }
        //分管负责人权限
        List<OrganizeHeadNextVo> organizeHeadNextDtoList = organizeDetails.getOrganizeHeadNextDtoList();
        if (!CollectionUtils.isEmpty(organizeHeadNextDtoList)) {
            OrganizeHeadNextVo first = organizeHeadNextDtoList.getFirst();
            if (StringUtils.isNotEmpty(first.getPower())) {
                organizeDetails.setNextPower(first.getPower());
            }
        }
        //成员数量
        List<OrganizeMemberVo> organizeMemberVoList = this.baseMapper.getOrganizeMemberVoList(id);
        organizeDetails.setMemberCount(organizeMemberVoList.size());
        return organizeDetails;
    }

    public List<CommonVo> getCollegeList(String name) {
        return this.baseMapper.getCollegeList(name);
    }

    public List<CommonVo> getDepartmentList(String name) {
        return this.baseMapper.getDepartmentList(name);
    }


    public List<CommonVo> getCollegeListPart() {
        return this.baseMapper.getCollegeListPart();
    }
}
